//
//  ActivityInfoViewController.m
//  SDSY
//
//  Created by 蓝布鲁 on 2017/4/4.
//  Copyright (c) 2017 蓝布鲁. All rights reserved.
//

#import "ActivityInfoViewController.h"
#import "ActivityInfoModel.h"
#import "ActivityInfoHeaderCell.h"
#import "ActivityInfoDetailCell.h"
#import "ActivityInfoTeacherCell.h"
#import "ActivityInfoDescriptionCell.h"
#import "UserInfoModel.h"
#import "OrderActivityButton.h"
#import <AVFoundation/AVFoundation.h>
#import "SigninViewController.h"

@interface ActivityInfoViewController ()<UITableViewDataSource,UITableViewDelegate>

// 视图
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)OrderActivityButton *orderBtn;

// 数据
@property (nonatomic, retain)ActivityInfoModel *infoModel;

@end

@implementation ActivityInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"活动详情";
    self.view.backgroundColor = UIColor.whiteColor;

    // 设置视图
    [self setupView];

    // 刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self updateView];
    }];
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - 自定义方法
-(void)setupView {
    // 初始化tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 40)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.tableView];

    // 预约活动
    self.orderBtn = [[OrderActivityButton alloc] initWithFrame:CGRectMake(0, self.tableView.bottomY, SCREEN_WIDTH, 40)];
    [self.orderBtn tappedWithTarget:self action:@selector(orderBtnTapped)];
    [self.view addSubview:self.orderBtn];
}

// 用code获取button状态
-(OrderActivityButtonType)buttonTypeWithCode:(NSInteger)code {
    switch (code){
        case 1:     // 可取消
            return CancelActivityEnable;
        case 3:     // 不可取消
            return CancelActivityDisable;
        case 2:     // 可预约
            return OrderActivityEnable;
        case 4:     // 不可预约
            return OrderActivityDisable;
        case 5:     // 活动已签到
            return ActivityHadSignInDisable;
        case 6:     // 活动已开始，进行签到
            return SignInActivityEnable;
        case 7:      // 未评价
            return CheckEvaluateDisable;
        case 8:     // 已评价
            return CheckEvaluateEnable;
        case 9:     // 活动进行中
            return DoingActivityDisable;
        case 10:      // 未参加此次活动，活动已结束
            return ActivityFinishedDisable;
        case 11:        // 第一次活动结束，第二次未开始
            return ActivityMiddleDisable;
    }
    return 0;
}

// 预约活动
-(void)orderActivity:(NSInteger)code {
    // 请求参数
    NSString *studentID = [UserInfoModel shareInstance].stu_id;
    NSString *token = [UserInfoModel shareInstance].token;
    NSDictionary *parameters = @{@"s_id": studentID, @"act_id": @(self.activityID), @"token": token, @"code": @(code)};


    // 请求网络
    [[NetworkTool shareInstance] requireMethodType:POSTType
                                         URLString:@"SDSY/addActivity"
                                        parameters:parameters
                                           success:^(NSDictionary *respondDictionary) {
                                               [SVProgressHUD dismiss];
                                               // 取出活动预约状态
                                               NSInteger reCode = [respondDictionary[@"Activiting"][@"code"] intValue];
                                               if(reCode == 12){
                                                   [SVProgressHUD showErrorWithStatus:@"上次预约未到场，进制预约一次"];
                                                   return;
                                               }
                                               // 更新活动状态
                                               self.infoModel.code = reCode;

                                               // 改变按钮状态
                                               [self.orderBtn setType:[self buttonTypeWithCode:reCode] signinTimes:0];

                                               // 提示预约成功
                                               if(reCode == 1) {
                                                   [SVProgressHUD showSuccessWithStatus:@"预约成功,请准时参加书院活动"];
                                               } else if (reCode == 2) {
                                                   [SVProgressHUD showSuccessWithStatus:@"取消预约成功"];
                                               } else if (reCode == 3) {

                                               }

                                           } failure:^(NSError *error) {
                [SVProgressHUD dismiss];
                [SVProgressHUD showfailed];
            }];
}

// 查看评价
-(void)checkEvaluate {
    [SVProgressHUD dismiss];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                        message:[NSString stringWithFormat:@"您已获得%d学分!",self.infoModel.grade]
                                                                 preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    
    [alert addAction:action];
    [self presentViewController:alert animated:true completion:nil];
}

// 签到
- (void)signinActivity{
    [SVProgressHUD dismiss];
    // 1.获取物理摄像头
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        // 如果能获取到设备,判断摄像头权限
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        
        if (status == AVAuthorizationStatusNotDetermined) {
            // 如果权限还未确定,则请求相机权限
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    // 如果同意了相机权限
                    NSLog(@"用户同意了相机权限");
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 跳转扫描界面
                        SigninViewController *signinViewController = [[SigninViewController alloc] init];
                        [self.navigationController pushViewController:signinViewController animated:true];
                    });
                } else {
                    // 如果拒绝了权限
                    NSLog(@"用户拒绝了相机权限");
                }
            }];
        } else if (status == AVAuthorizationStatusAuthorized) {
            // 如果已经同意了相机权限,跳转扫描界面
            SigninViewController *signinViewController = [[SigninViewController alloc] init];
            [self.navigationController pushViewController:signinViewController animated:true];
        } else if (status == AVAuthorizationStatusDenied) {
            // 如果权限被拒绝
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"⚠️ 警告"
                                                                                     message:@"请去-> [设置 - 隐私 - 相机 - 尚德书院] 打开访问开关"
                                                                              preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:action];
            [self presentViewController:alertController animated:true completion:nil];
        } else if (status == AVAuthorizationStatusRestricted) {
            // 如果系统相机权限未开启
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"⚠️ 警告"
                                                                                     message:@"由于系统权限未开启,无法打开摄像头"
                                                                              preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:action];
            [self presentViewController:alertController animated:true completion:nil];
        }
        
    } else {
        // 如果获取不到设备
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"⚠️ 警告"
                                                                                 message:@"未检测到摄像头"
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:action];
        [self presentViewController:alertController animated:true completion:nil];
    }
}


#pragma mark - 事件监听

-(void)orderBtnTapped{
    [SVProgressHUD show];

    if(self.orderBtn.type == CancelActivityEnable){
        // 预约或取消预约活动
        [self orderActivity:1];
    }else if (self.orderBtn.type == OrderActivityEnable){
        // 预约或取消预约活动
        [self orderActivity:2];
    }else if (self.orderBtn.type == CheckEvaluateEnable){
        // 查看评价
        [self checkEvaluate];
    }else if (self.orderBtn.type == SignInActivityEnable){
        [self signinActivity];
    }


}

#pragma mark - 网络获取数据
-(void)updateView {

    // 获取Cell数据
    [[NetworkTool shareInstance] requireMethodType:POSTType
                                         URLString:@"SDSY/getActivityInfo"
                                        parameters:@{@"act_id": @(self.activityID), @"s_id":[UserInfoModel shareInstance].stu_id}
                                           success:^(NSDictionary *respondDictionary) {
                                               self.infoModel = [[ActivityInfoModel alloc] initWithDictionary:respondDictionary];
                                               [self.tableView reloadData];
                                               [self.tableView.mj_header endRefreshing];

                                               // 判断是否已经是预约过的活动
                                               [self.orderBtn setType:[self buttonTypeWithCode:self.infoModel.code] signinTimes:self.infoModel.time];

                                           } failure:^(NSError *error) {
                [SVProgressHUD showfailed];
                [self.tableView.mj_header endRefreshing];
            }];

}


#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ActivityInfoBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELLID"];
    if (cell == nil) {
        if(indexPath.row == 0) {
            // 头部cell
            cell = [[ActivityInfoHeaderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELLID"];
        }if (indexPath.row == 1) {
            // 活动开始结束时间
            cell = [[ActivityInfoDetailCell alloc] initWithCellType:ActivityInfoDetailCellStartTimeType];
        }if (indexPath.row == 2) {
            // 活动地点
            cell = [[ActivityInfoDetailCell alloc] initWithCellType:ActivityInfoDetailCellLocationType];
        }if(indexPath.row == 3) {
            // 活动已报名人数
            cell = [[ActivityInfoDetailCell alloc] initWithCellType:ActivityInfoDetailCellOrderedNumberType];
        }if(indexPath.row == 4) {
            // 活动已可获得学分
            cell = [[ActivityInfoDetailCell alloc] initWithCellType:ActivityInfoDetailCellCanGetCreditType];
        }if(indexPath.row == 5) {
            // 导师介绍
            cell = [[ActivityInfoTeacherCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELLID"];
        }if (indexPath.row == 6) {
            cell = [[ActivityInfoDescriptionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELLID"];
        }
    }

    // 设置数据
    cell.model = self.infoModel;

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 0) {
        // 顶部显示
        return [tableView cellHeightForIndexPath:indexPath
                                    model:self.infoModel
                                  keyPath:@"model"
                                cellClass:[ActivityInfoHeaderCell class]
                         contentViewWidth:SCREEN_WIDTH];

    } else if (indexPath.row >= 1 && indexPath.row <= 4) {
        // 活动详情
        return 40;
    } else if (indexPath.row == 5) {
        // 导师介绍
        return [tableView cellHeightForIndexPath:indexPath
                                           model:self.infoModel
                                         keyPath:@"model"
                                       cellClass:[ActivityInfoTeacherCell class]
                                contentViewWidth:SCREEN_WIDTH];
    } else if(indexPath.row == 6) {
        // 活动简介
        return [tableView cellHeightForIndexPath:indexPath
                                           model:self.infoModel
                                         keyPath:@"model"
                                       cellClass:[ActivityInfoDescriptionCell class]
                                contentViewWidth:SCREEN_WIDTH];
    }
    return 0;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
}




@end
